import { useRequest } from "ahooks";
import { GET_USERS, ADD_USER, EDIT_USER, DELETE_USER } from "./api/userApi";
import axios from "axios";

function Index() {
  // query
  const { data, loading, error } = useRequest(async () => {
    const res = await axios.get(GET_USERS);
    return res.data;
  });

  // add
  const { runAsync: addRunAsync } = useRequest(
    async (params: { name: string; age: number }) => {
      const res = await axios.post(ADD_USER, params);
      return res.data;
    },
    {
      manual: true,
    }
  );

  // edit
  const { runAsync: editRunAsync } = useRequest(
    async (params: { id: number; name: string; age: number }) => {
      const res = await axios.put(EDIT_USER + "/" + params.id, params);
      return res.data;
    },
    {
      manual: true,
    }
  );

  // del
  const { runAsync: delRunAsync } = useRequest(
    async (params: { id: number }) => {
      const res = await axios.delete(DELETE_USER + "/" + params.id, {
        data: params,
      });
      return res.data;
    },
    {
      manual: true,
    }
  );

  const add = async () => {
    const result = await addRunAsync({ name: "张三", age: 20 });
    if (result.code === 200) {
      data.users.push({ id: data.users.length + 1, name: "张三", age: 20 });
    }
  };

  const edit = async () => {
    const result = await editRunAsync({ id: 1, name: "李四", age: 21 });
    if (result.code === 200) {
      data.users[0] = { id: 1, name: "李四", age: 21 };
    }
  };

  // del
  const del = async () => {
    const result = await delRunAsync({ id: 1 });
    if (result.code === 200) {
      data.users.splice(0, 1);
    }
  };
  return (
    <>
      {loading ? (
        <div>加载中...</div>
      ) : error ? (
        <div>加载失败: {error.message}</div>
      ) : (
        <ul>
          {data?.users.map(
            (user: { id: number; name: string; age: number }) => (
              <li key={user.id}>
                姓名: {user.name}, 年龄: {user.age}
              </li>
            )
          )}
        </ul>
      )}
      <button
        onClick={() => {
          add();
        }}
      >
        添加用户
      </button>
      <button
        onClick={() => {
          edit();
        }}
      >
        修改用户
      </button>
      <button
        onClick={() => {
          del();
        }}
      >
        删除用户
      </button>
    </>
  );
}

export default Index;
